/*
 * Part of the NXT bluetooth remote control J2ME applet.
 * Copyright (C) 2007-2008 Alexander Demin, <alexander@demin.ws>
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You can redistribute this file and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your discretion) any later version.
 * See the accompanying file "COPYING.txt" for more details.
 */
import java.io.*;
import java.util.*;
import javax.microedition.io.*;

public class NxtBrick {

   NxtReaderThread reader;

   StreamConnection con;

   String url;

   OutputStream os;
   InputStream is;

   NxtMidlet.Logger logger;

   NxtBrick(NxtMidlet.Logger aLogger) {
      logger = aLogger; 
   }

   public void connect() throws Exception {

      NxtBluetooth nxtBluetooth = new NxtBluetooth(logger);

      try {
         nxtBluetooth.find();

         url = nxtBluetooth.getURL();
         logger.line( url );

      } catch( java.io.IOException e ) {
         logger.line( e.getMessage() );
         throw new Exception( "No NXT found" );
      }
      
      try {

         con = (StreamConnection)Connector.open(url);

         os = con.openOutputStream();
         is = con.openInputStream();
            
         reader = new NxtReaderThread(logger, is, os);

         reader.start();

      } catch( java.io.IOException e ) {
         logger.line( e.getMessage() );
         throw new Exception( "Connection failed to " + url );
      }

   }

   public void disconnect() {
      reader.terminate();
      reader = null;

      con = null;
   }

   public int avail() { return reader.getInAvail(); }

   public Vector messages() { return reader.getMessages(); }

   public void send( int mailbox, String s ) {
      NxtMessage msg = new NxtMessage( NxtMessage.INCOMING, mailbox, s, false );
      try {
         os.write( msg.pack() );
         os.flush();
      } catch( java.io.IOException e ) {
         logger.line( e.getMessage() );
      }
   }
}
